package com.example.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
 * countdownlatch 是一个同步类工具，不涉及锁定，当count的值为零时当前线程继续运行，
 * 不涉及同步，只涉及线程通信的时候，使用它较为合适
 * 如果有资源争夺 还是需要加锁
 */
public class NotifyFreeLock2CDL {
    //添加volatile，使t2能够得到通知
    static volatile List lists = new ArrayList();

    public  void add(Object o) {
        lists.add(o);
    }

    public static void main(String[] args) {
        // 声明CountDownLatch
        CountDownLatch countDownLatch = new CountDownLatch(4);
        CountDownLatch countDownLatch2 = new CountDownLatch(1);
        Thread t1=new Thread(()->{
            for(int i=0;i<10;i++){
                lists.add(new Object());
                System.out.println("线程1添加数据"+lists.size());
                countDownLatch.countDown();
                try {
                    if (lists.size()==5){
                        countDownLatch2.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2=new Thread(()->{
            try {
                countDownLatch.await();
                System.out.println("线程2开始执行==="+lists.size());
                countDownLatch2.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
    }
}
